const app = require('express')(); 
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const static = require('express-static');
app.use(static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
  res.send(fs.readFileSync(path.join(__dirname, 'public/index.html'), 'utf-8'));
})

app.get('/result', async (req, res) => {
  const resultHtml = fs.readFileSync(path.join(__dirname, 'public/result.html'), 'utf-8');
  const { code, error } = req.query;
  if(code) { // 用户同意授权
    console.log('code', code );
    // 拿到code，去换取access_token
    const data = await axios.post(`https://github.com/login/oauth/access_token`, {
      client_id: 'f5c57b96186522232505',
      client_secret: '21db298423598d2e50a3217bea99e81ae68583e2',
      code,
      redirect_uri: 'http://localhost:8080/result'
    });
    const access_token = data.data.split('&')[0].split('=')[1];
    console.log('access_token', access_token);
    // 携带access_token去获取用户信息
    const result = await axios.get(`https://api.github.com/user`, {
      headers: {
        Authorization: `Bearer ${access_token}`
      }
    });
    console.log('用户信息', result.data);
    // 进行入库操作。
    // 创建token
    res.send(resultHtml.replace('<!--result-->','登录成功！'));
    return;
  }
  if(error) { // 用户拒绝授权
    res.send(resultHtml.replace('<!--result-->','取消授权！登录失败！'));
    return;
  }
})

app.listen(8080, () => {
  console.log('server is running at http://localhost:8080')
})